import { Result } from '@/service/request/type';
import { Message } from '@/instance';
import Modal from '@/components/q-modal/index.vue';
import { isArray } from '@/utils';

export default (
    tableRef: any,
    delIds: Ref<Array<number | string>>,
    doDelAction: (params: number[]) => Promise<Result<any>>
) => {
    /**
     * @: 行内删除
     * @param {T} row
     * @return {*}
     */
    const rowDel = async function (row: any, cb?: () => void | Promise<void>) {
        try {
            if (arguments.length === 1) row.btnLoading = true;

            await doDelAction(isArray(row) ? row : [row.id]);
            tableRef.value.clearSelection(); // 清空所有选择选项

            Message.success('删除成功！');

            tableRef.value?.getData?.();
            if (typeof cb === 'function') cb();
        } catch (error) {
            console.log('error', error);
        } finally {
            if (arguments.length === 1) row.btnLoading = false;
        }
    };

    /**
     * @: 按钮删除
     * @return {*}
     */
    const handleDel = (msg?: string) => {
        Modal.confirm({
            title: '确认删除',
            content: msg || '删除后该模具及相关数据将被清空，是否确认删除！',
            onOk: async () => {
                return await new Promise(async resolve => {
                    try {
                        await rowDel(delIds.value);
                        resolve('');
                    } catch (error) {
                        return console.log('Oops errors!');
                    }
                });
            }
        });
    };
    return {
        handleDel,
        rowDel
    };
};
